<template>
  <div class="py-[24px] flex overflow-auto" ref="scrollContainer">
    <div class="m-auto w">
      <n-spin :show="goodsLoading">
        <div class="relative flex items-center gap-2 px-2 bg-white">
          <img
            :src="
              goods.productImage?.whiteImage ||
              (goods.productImage?.images?.length ? goods.productImage?.images[0] : '')
            "
            class="w-[60px] h-[60px] ml-2"
          />

          <div class="text-[18px] font-[300] py-2">
            <div>
              <n-ellipsis :line-clamp="1" :tooltip="false">
                {{ goods.subjectTrans }}
              </n-ellipsis>
            </div>
            <div class="text-[--main-color] text-[16px] text-left">
              <span
                class="cursor-pointer"
                @click="router.push(`/store/${goods.sellerOpenId}`)"
              >
                {{ $t("button.进入店铺") }}
              </span>
              <!-- {{ goods.sellerOpenId }} -->
            </div>
          </div>

          <!-- <div class="text-center bg-[--main-color] text-[#fff] h-[78px] flex items-center">
          <div>Productos Similares</div>
        </div> -->
        </div>
      </n-spin>
      <div class="w m-auto mt-[24px]">
        <div class="w m-auto mt-[24px] grid grid-cols-5 gap-4" v-if="!noResult">
          <div class="flex-1" v-for="item in goodsList" :key="item.offerId">
            <goodsCard :goods="item"></goodsCard>
          </div>
        </div>

        <template v-else>
          <div
            class="w-[700px] mx-auto text-center my-[110px] text-[22px] font-[400] text-[#2f2f2f] leading-[36px]"
          >
            {{ $t("tips.未搜索到商品") }}
          </div>
        </template>
      </div>

      <div class="w text-center p-[100px]" v-show="loading && !showPageBar">
        <n-spin size="medium" />
      </div>

      <div class="flex mt-[24px]" v-if="showPageBar">
        <n-button
          :loading="loading"
          type="primary"
          class="m-auto"
          @click="onClickLoadMore"
          ghost
        >
          {{ $t("button.加载更多") }}
        </n-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { getCommodityDetail, recommendSearch } from "@/api/product";
import { useRoute, useRouter } from "vue-router";
import goodsCard from "@/components/goodsCard.vue";
import bus from "@/utils/mitt";
const route = useRoute();
const router = useRouter();
const goodsLoading = ref(false);
const loading = ref(false);
const goods = ref({});
const goodsList = ref([]);
const result = ref({
  currentPage: 0,
  totalPage: 1,
});
const request = ref({
  pageNo: 1,
  pageSize: 10, //1688 只能10
});
const noResult = ref(false);
const scrollContainer = ref(null);
const canLoadMore = computed(
  () => !loading.value && result.value.currentPage <= result.value.totalPage
);
const showPageBar = ref(false);

const maxPage = 5;

const initSearch = () => {
  request.value.pageNo = 1;
  goodsList.value = [];
  showPageBar.value = false;

  commoditySearchHandle();
};

onMounted(async () => {
  const id = route.params.id;
  goodsLoading.value = true;
  const { data } = await getCommodityDetail(id);
  goodsLoading.value = false;
  goods.value = data.data;
  initSearch(true);
});

onUnmounted(() => {
  bus.off("searchByKeyword");
});

const commoditySearchHandle = async () => {
  if (!canLoadMore.value) return;
  loading.value = true;
  try {
    const { data } = await recommendSearch({
      offerId: goods.value.offerId,
      language: "es",
      ...request.value,
    });

    console.log("%c Line:102 🍋 data", "color:#ffdd4d", data);

    // const { currentPage, pageSize, totalPage, totalRecords } = data.data;

    // result.value = { currentPage, pageSize, totalPage, totalRecords };
    // request.value.page = currentPage;
    if (!data.data) {
      //本次查询没有结果
      noResult.value = !goodsList.value || goodsList.value.length === 0;
    } else {
      goodsList.value.push(...data.data);
      noResult.value = false;
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  window.addEventListener("scroll", handleScroll);
});

onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});

// 滚动事件处理器
const handleScroll = () => {
  //   if (!loadMoreTrigger.value || !scrollContainer.value) return;
  const scrollTop = window.scrollY;
  const documentHeight = Math.max(
    document.body.scrollHeight,
    document.documentElement.scrollHeight
  );
  const windowHeight = window.innerHeight;

  // 判断是否触底
  if (scrollTop + windowHeight >= documentHeight - 500 && canLoadMore.value) {
    if (request.value.pageNo >= maxPage || showPageBar.value) {
      showPageBar.value = true;
      return;
    }
    request.value.pageNo += 1;
    commoditySearchHandle();
  }
};

const onClickLoadMore = async () => {
  request.value.pageNo += 1;
  commoditySearchHandle();
};
</script>

<style lang="scss" scoped>
.search-items {
  border-bottom: 1px solid #d8d8d8;
  &:last-child {
    border-bottom: none;
  }
}

.sort-wrapper {
  position: relative;
  width: 16px;
  i {
    position: absolute;
    right: 0;
    color: #cccccc;
    &:first-child {
      bottom: -3px;
    }
    &:last-child {
      top: -3px;
    }
  }
}
</style>
